package com.rivues.module.design.web.handler.player;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import oracle.sql.TIMESTAMP;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.account.web.handler.LoginController;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.model.AnalyzerReport;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.CubeLevel;
import com.rivues.module.platform.web.model.CubeMeasure;
import com.rivues.module.platform.web.model.CubeMetadata;
import com.rivues.module.platform.web.model.Database;
import com.rivues.module.platform.web.model.Dimension;
import com.rivues.module.platform.web.model.DrillDown;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.PublishedCube;
import com.rivues.module.platform.web.model.ReportCellMerge;
import com.rivues.module.platform.web.model.ReportCol;
import com.rivues.module.platform.web.model.ReportFilter;
import com.rivues.module.platform.web.model.ReportOperations;
import com.rivues.module.platform.web.model.SearchResultTemplet;
import com.rivues.module.platform.web.model.StyleBean;
import com.rivues.module.platform.web.model.TypeCategory;
import com.rivues.module.platform.web.model.Warning;
import com.rivues.module.report.web.handler.ReportHandler;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.data.ReportData;
import com.rivues.util.iface.cube.CubeFactory;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.local.LocalTools;
import com.rivues.util.serialize.JSON;
import com.rivues.util.service.cache.CacheHelper;
import com.rivues.util.tools.H2Helper;
  
@Controller  
@RequestMapping("/{orgi}/design/player")  
public class PlayerDesignController extends ReportHandler{  
//	private final Logger log = LoggerFactory.getLogger(LogIntercreptorHandler.class); 
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}" , name="querydesign" , type="design",subtype="query")
    public ModelAndView querydesign(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/index") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	if(report.getHtml()!=null && report.getHtml().equals("1")){
    		//允许匿名用户从移动端访问报表
    	}else if(super.getUser(request).getUsername().equals(RivuDataContext.GUEST_USER)){
    		return new LoginController().login(request, orgi) ;
    	}
    	
    	view.addObject("publishedCubeList", CubeFactory.getCubeInstance().getPublishedCubeList(orgi , super.getUser(request))) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(reportModel==null){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	
    	/**
    	 * 设置参数
    	 */
    	super.processRequestParam(analyzerReport, request , false) ;
    	
    	if(reportModel != null){
	    	/**
	    	 * 以下代码用于
	    	 */
	    	for(ReportFilter reportFilter : RivuTools.getRequestFilters(analyzerReport.getFilters())){
	    		if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype())){
	    			if(request.getParameter(reportFilter.getCode()+"_start")!=null && request.getParameter(reportFilter.getCode()+"_end")!=null){
		    			if(RivuDataContext.FilterConValueEnum.AUTO.toString().equals(reportFilter.getConvalue())){
		    				String start = request.getParameter(reportFilter.getCode()+"_start")!=null ? request.getParameter(reportFilter.getCode()+"_start") : "" ;
		    				String end = request.getParameter(reportFilter.getCode()+"_end")!=null ? request.getParameter(reportFilter.getCode()+"_end") : "" ;
		    				if((start.length() - start.replaceAll(".", "").length()) != (end.length() - end.replaceAll(".", "").length())){
		    					continue ;
		    				}
		    			}
		    			reportFilter.setRequeststartvalue(request.getParameter(reportFilter.getCode()+"_start")) ;
		    			reportFilter.setRequestendvalue(request.getParameter(reportFilter.getCode()+"_end")) ;
	    			}
	    		}else{
		    		if(request.getParameter(reportFilter.getCode())!=null){
		    			reportFilter.setRequestvalue(request.getParameter(reportFilter.getCode())) ;
		    		}
	    		}
	    	}
	    	/**
	    	 * 进入数据表如果没有选中列则全部选中
	    	 */
//	    	PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
//			if(publishedCube!=null){
//				Cube cube = publishedCube.getCube() ;
//				if("table".equals(cube.getDstype())){
//					if (reportModel != null && (reportModel.getMeasure() == null || (reportModel.getMeasure() != null&&reportModel.getMeasure().trim().length()==0))) {
//						StringBuffer sb = new StringBuffer();
//						for(CubeMeasure measure : cube.getMeasure()) {
//							if(sb.toString().length()>0){
//								sb.append(",");
//							}
//							sb.append(measure.getId());
//						}
//						reportModel.setMeasure(sb.toString());
//					}
//				}
//				
//			}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	/**
    	 * 创建视图
    	 */
    	/**
    	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    	 */
    	return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/resetreport/{reportid}" , name="querydesignreset" , type="design",subtype="query")
    public ModelAndView querydesignreset(HttpServletRequest request , @PathVariable String orgi,@PathVariable String reportid) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("redirect:/{orgi}/design/player/{reportid}.html") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel savemodel = null ; 
    	PublishedCube cube = null ; 
    	if(request.getParameter("modelid")!=null && request.getParameter("modelid").length()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(request.getParameter("modelid").equals( model.getId())){
    				savemodel = model ;
    				if(request.getParameter("cubeid")!=null && request.getParameter("cubeid").length()>0){
    					cube = CubeFactory.getCubeInstance().getCubeByID(request.getParameter("cubeid"));
    					model.setPublishedcubeid(cube.getId()) ;
        				model.setName(cube.getName());
    				}else{
    					model.setPublishedcubeid(null) ;
        				model.setName(null);
    				}
    				clearAnalyzerReportModel(model);
    				break;
    			}
    		}
    	}else{
	    	if(request.getParameter("cubeid")!=null && request.getParameter("cubeid").length()>0){
	    		AnalyzerReportModel model = new AnalyzerReportModel();
	    		savemodel = model ;
				cube = CubeFactory.getCubeInstance().getCubeByID(request.getParameter("cubeid"));
				model.setId(String.valueOf(System.currentTimeMillis()));
				model.setPublishedcubeid(cube.getId()) ;
				model.setName(cube.getName());
				model.setOrgi(orgi);
				model.setReportid(reportid);
				model.setDstype(RivuDataContext.CubeEnum.CUBE.toString());
				/**
				 * 清空报表所有内容
				 */
				analyzerReport.getModel().clear();
				analyzerReport.getFilters().clear();
				//清空结束
				analyzerReport.getModel().add(model) ;
	    	}else{
	    		/**
				 * 清空报表所有内容
				 */
				analyzerReport.getModel().clear();
				analyzerReport.getFilters().clear();
				//清空结束
				analyzerReport.getModel().clear();
	    	}
    	}
    	
    	/**
    	 * 保存 模型和  cube 的对应关系， 以及保存 维度和指标， 用于指标字典
    	 */
    	saveCubeInUser(savemodel, reportid, orgi, report);
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	return view ;
    }
    /**
     * 将reportModel重置
     * @param model
     */
    private void clearAnalyzerReportModel(AnalyzerReportModel model){
    	if(model!=null){
    		model.setRowdimension("") ;
    		model.setColdimension("") ;
    		model.setMeasure("");
    		model.setRowformatstr("") ;
    		model.setColformatstr("") ;
    	}
    }
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/modelinit/{reportid}/{modelid}" , name="modelinit" , type="design",subtype="query")
    public ModelAndView modelinit(HttpServletRequest request , @PathVariable String orgi,@PathVariable String modelid, @PathVariable String reportid , @Valid String oid, @Valid String type) throws Exception{  
    	return designreport(request , orgi , modelid , reportid , oid  , type , "left") ; 
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/designreport/{reportid}/{modelid}" , name="designreport" , type="design",subtype="query")
    public ModelAndView designreport(HttpServletRequest request , @PathVariable String orgi,@PathVariable String modelid, @PathVariable String reportid , @Valid String oid, @Valid String pos,@Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
	    	if(type.equals(RivuDataContext.QueryReportDragEnum.DIMENSIONS.toString())){
	    		StringBuffer strb = new StringBuffer();
	    		if(pos!=null && (pos.equals("top") || pos.equals("bottom"))){	//拖拽位置在 列上
	    			if(reportModel.isExchangerw()){
	    				strb.append(reportModel.getRowdimension()!=null ? reportModel.getRowdimension() : "") ;
			    		for(String rowid : oid.split(",")){
			    			if(reportModel.getColdimension()==null || reportModel.getColdimension().indexOf(rowid)<0){
				    			if(reportModel.getRowdimension()!=null && reportModel.getRowdimension().indexOf(rowid)<0){
				    				if(strb.length()>0){
				    					strb.append(",") ;
				    				}
				    				strb.append(rowid) ;
				    			}
			    			}
			    		}
			    		reportModel.setRowdimension(strb.toString()) ;
	    			}else{
		    			strb.append(reportModel.getColdimension()!=null ? reportModel.getColdimension() : "") ;
			    		for(String rowid : oid.split(",")){
			    			if(reportModel.getRowdimension()==null || reportModel.getRowdimension().indexOf(rowid)<0){
				    			if(reportModel.getColdimension()!=null && reportModel.getColdimension().indexOf(rowid)<0){
				    				if(strb.length()>0){
				    					strb.append(",") ;
				    				}
				    				strb.append(rowid) ;
				    			}
			    			}
			    		}
			    		reportModel.setColdimension(strb.toString()) ;
	    			}
	    		}else{								//拖拽位置在 行上
	    			if(reportModel.isExchangerw()){
	    				strb.append(reportModel.getColdimension()!=null ? reportModel.getColdimension() : "") ;
			    		for(String rowid : oid.split(",")){
			    			if(reportModel.getRowdimension()==null || reportModel.getRowdimension().indexOf(rowid)<0){
				    			if(reportModel.getColdimension()!=null && reportModel.getColdimension().indexOf(rowid)<0){
				    				if(strb.length()>0){
				    					strb.append(",") ;
				    				}
				    				strb.append(rowid) ;
				    			}
			    			}
			    		}
			    		reportModel.setColdimension(strb.toString()) ;
	    			}else{
	    				strb.append(reportModel.getRowdimension()!=null ? reportModel.getRowdimension() : "") ;
			    		for(String rowid : oid.split(",")){
			    			if(reportModel.getColdimension()==null || reportModel.getColdimension().indexOf(rowid)<0){
				    			if(reportModel.getRowdimension()!=null && reportModel.getRowdimension().indexOf(rowid)<0){
				    				if(strb.length()>0){
				    					strb.append(",") ;
				    				}
				    				strb.append(rowid) ;
				    			}
			    			}
			    		}
			    		reportModel.setRowdimension(strb.toString()) ;
	    			}
	    		}
	    	}else if(type.equals(RivuDataContext.QueryReportDragEnum.MEASURE.toString())){
	    		StringBuffer strb = new StringBuffer();
	    		strb.append(reportModel.getMeasure()!=null ? reportModel.getMeasure() : "") ;
	    		for(String rowid : oid.split(",")){
	    			if(reportModel.getMeasure()!=null && reportModel.getMeasure().indexOf(rowid)<0){
	    				if(strb.length()>0){
	    					strb.append(",") ;
	    				}
	    				strb.append(rowid) ;
	    			}
	    		}
	    		reportModel.setMeasure(strb.toString()) ;
	    	}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
		/**
    	 * 重新获取视图数据，同样，报表数据也在此方法中加载，即拖拽后立即生效
    	 */
    	return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    @RequestMapping(value = "countview/{reportid}/{modelid}", name="countview" , type="design",subtype="custom")
	public ModelAndView countview(HttpServletRequest request , @PathVariable String  orgi ,  @PathVariable String  reportid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/countview") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	view = createModelAndView(view , true , report , request , reportModel);
    	if(view.getModelMap().get("reportData")!=null){
    		ReportData reportData = (ReportData) view.getModelMap().get("reportData") ;
			if(reportData.getCol()!=null){
				List<String> coltitles = new ArrayList<String>();
				for (com.rivues.util.data.Level col : reportData.getCol().getChilderen()) {
					coltitles.add(col.getName());
				}
				view.addObject("coltitles", coltitles) ;
				if(!StringUtils.isBlank(reportModel.getHiddencolstr())){
					view.addObject("existtitles", JSON.parseObject(reportModel.getHiddencolstr(), String[].class)) ;
				}
				
			}
    	}
    	return view;
	}
    
    
    @RequestMapping(value = "countviewdo/{reportid}/{modelid}", name="countviewdo" , type="design",subtype="custom")
	public ModelAndView countviewdo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid,  @Valid String[] colnames,@Valid String pageNo) throws Exception{
    	ResponseData responseData = new ResponseData("/pages/design/player/countviewlist");
    	ModelAndView view = request(responseData , orgi) ;
    	StringBuffer sqlsb = new StringBuffer();
    	StringBuffer sumsb = new StringBuffer();
    	StringBuffer avgsb = new StringBuffer();
    	StringBuffer countsb = new StringBuffer();
    	StringBuffer groupsb = new StringBuffer();
    	List<String> heads = new ArrayList<String>();
    	List<List<String>> data = new ArrayList<List<String>>();
    	boolean flag = false;
    	for (String colname : colnames) {
			if(request.getParameter("type_"+colname).equals("group")){
				if(groupsb.toString().length()>0){
					groupsb.append(",");
					sqlsb.append(",");
				}else{
					groupsb.append(" group by ");
					sqlsb.append("select ");
				}
				groupsb.append(colname);
				flag = true;
				sqlsb.append(colname);
				
			}else if(request.getParameter("type_"+colname).equals("count")){
				if(countsb.toString().length()>0){
					countsb.append(",");
				}
				countsb.append("count(");
				countsb.append(colname);
				countsb.append(")");
			}else if(request.getParameter("type_"+colname).equals("avg")){
				if(avgsb.toString().length()>0){
					avgsb.append(",");
				}
				avgsb.append("avg(");
				avgsb.append(colname);
				avgsb.append(")");
			}else if(request.getParameter("type_"+colname).equals("sum")){
				if(sumsb.toString().length()>0){
					sumsb.append(",");
				}
				sumsb.append("sum(");
				sumsb.append(colname);
				sumsb.append(")");
			}
		}
    	if(sqlsb.length()==0){
    		sqlsb.append("select ");
    	}
    	
    	if(countsb.length()>0){
    		if(flag){
    			sqlsb.append(",");
    		}
    		sqlsb.append(" ").append(countsb);
    		flag = true;
    	}
    	if(avgsb.length()>0){
    		if(flag){
    			sqlsb.append(",");
    		}
    		sqlsb.append(" ").append(avgsb);
    		flag = true;
    	}
    	if(sumsb.length()>0){
    		if(flag){
    			sqlsb.append(",");
    		}
    		sqlsb.append(" ").append(sumsb);
    	}
    	sqlsb.append(" from ");
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
    	Cube cube = publishedCube.getCube();
    	CubeMetadata meta = cube.getMetadata().get(0);
		if("2".equals(meta.getTb().getTabletype())){
			sqlsb.append(" (").append(meta.getTb().getDatasql()).append(") ") ;
		}else{
			sqlsb.append(" ").append(meta.getTb().getName()).append(" ") ;
		}
		sqlsb.append(" ").append(groupsb);
		Database db = (Database)super.getService().getIObjectByPK(Database.class, cube.getDb());
		int p = Integer.parseInt(pageNo);
		if(p<1)p=1;
		int ps = 100;
		int startindex = (p - 1) * ps;
		String sql = null;
		if (RivuDataContext.DataBaseTYPEEnum.MYSQL.toString().equalsIgnoreCase(db.getSqldialect())) {
			sql = new StringBuilder(sqlsb.toString()).append(" LIMIT ").append(
					startindex).append(",").append(ps).toString();
		}
		if (RivuDataContext.DataBaseTYPEEnum.HIVE.toString().equalsIgnoreCase(db.getSqldialect())) {
			sql = new StringBuilder(sqlsb.toString()).append(" LIMIT ").append(
					startindex+ps).toString();
		}
		if (RivuDataContext.DataBaseTYPEEnum.SQLSERVER.toString().equalsIgnoreCase(db.getSqldialect())) {

		}
		if(RivuDataContext.DataBaseTYPEEnum.POSTGRESQL.toString().equalsIgnoreCase(db.getSqldialect())){
			sql = new StringBuilder(sqlsb.toString()).append(" LIMIT ").append(ps).append(" offset ").append(startindex).toString();
		}
		if (RivuDataContext.DataBaseTYPEEnum.ORACLE.toString().equalsIgnoreCase(db.getSqldialect())) {
			sql = new StringBuilder()
					.append(
							"select * from ( select row_.*, rownum rownum_ from (")
					.append(sqlsb.toString()).append(") row_ where rownum <= ")
					.append(p * ps).append(") where rownum_ > ")
					.append(startindex).toString();
		}
		if(sql.length()>0){
    		
    		Connection connection = H2Helper.getConnection(db);
    		Statement statement = connection.createStatement() ;
    		ResultSet result = null;
    		try{
    			result = statement.executeQuery(sql.toString());
    			ResultSetMetaData result_meta = result.getMetaData();
    			
    			int colNum = result_meta.getColumnCount();
    			for (int i = 1; i <= colNum; i++) {
    				heads.add(result_meta.getColumnName(i));
    			}
    			List<String> rowdata = null;
    			while(result.next()){
					rowdata = new ArrayList<String>();
    				for (int i = 1; i <= colNum; i++) {
    					Object dataValue = result.getObject(i);
    					if(dataValue != null&&dataValue instanceof TIMESTAMP){
    						dataValue = TIMESTAMP.toTimestamp(((TIMESTAMP)dataValue).getBytes());
    					}
    					rowdata.add(dataValue.toString());
    					
        			}
    				data.add(rowdata);
    			}
    			view.addObject("heads", heads);
    			view.addObject("datas", data);
    		}catch(Exception ex){
    			ex.printStackTrace(); 
    			responseData.setPage("/pages/public/success");
    			view = request(responseData , orgi) ;
    			view.addObject("data", "查询出错："+ex.getMessage());
    		}finally{
    			if(result!=null)
        			result.close();
    			if(statement!=null)
    				statement.close();
    			if(connection!=null)
    				connection.close();
    			
    		}
    	}
    	
    	return view;
	}
    
    
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/rmmeasure/{reportid}/{modelid}" , name="rmmeasure" , type="design",subtype="query")
    public ModelAndView rmmeasure(HttpServletRequest request , @PathVariable String orgi,@PathVariable String modelid, @PathVariable String reportid , @Valid String oid, @Valid String pos,@Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		if(request.getParameter("type")!=null && request.getParameter("type").equals("measure")){
    			if(request.getParameter("oid")!=null && reportModel.getMeasure()!=null){
    	    		StringBuffer strb = new StringBuffer();
    	    		for(String mid : reportModel.getMeasure().split(",")){
    	    			if(!request.getParameter("oid").equals(mid)){
    	    				if(strb.length()>0){
    	    					strb.append(",") ;
    	    				}
    	    				strb.append(mid) ;
    	    			}
    	    		}
    	    		reportModel.setMeasure(strb.toString()) ;
    	    	}
    		}else {
    				if(request.getParameter("oid")!=null && reportModel.getRowdimension()!=null){
        				StringBuffer strb = new StringBuffer();
        				for(String mid : reportModel.getRowdimension().split(",")){
        					if(!request.getParameter("oid").equals(mid)){
        						if(strb.length()>0){
        							strb.append(",") ;
        						}
        						strb.append(mid) ;
        					}
        				}
        				reportModel.setRowdimension(strb.toString()) ;
        			}
    				if(request.getParameter("oid")!=null && reportModel.getColdimension()!=null){
    					StringBuffer strb = new StringBuffer();
    					for(String mid : reportModel.getColdimension().split(",")){
    						if(!request.getParameter("oid").equals(mid)){
    							if(strb.length()>0){
    								strb.append(",") ;
    							}
    							strb.append(mid) ;
    						}
    					}
    					reportModel.setColdimension(strb.toString()) ;
    				}
    		}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
		/**
    	 * 重新获取视图数据，同样，报表数据也在此方法中加载，即拖拽后立即生效
    	 */
    	return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/savereport" , name="savereport" , type="design",subtype="query")
    public ModelAndView savereport(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @Valid String oid, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/savereport") , orgi) ;
    	/**
    	 * 保存报表
    	 */
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request) , orgi, reportid,true);
//    	ReportFactory.getReportInstance().updateReport(ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true),super.getUser(request)) ;
    	if(report.getCreater()!=null && report.getCreater().equals(super.getUser(request).getId())){
	    	ReportFactory.getReportInstance().updateReport(report,super.getUser(request)) ;
	    	view.addObject("msg", LocalTools.getMessage("I_DESIGN_1000001")) ;
    	}else{
    		view.addObject("msg", LocalTools.getMessage("E_DESIGN_2000001")) ;
    	}
    	return view ;
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/savereportas" , name="savereportas" , type="design",subtype="query")
    public ModelAndView savereportas(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @Valid String oid, @Valid String type,@Valid String name) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/savereport") , orgi) ;
    	int count = ReportFactory.getReportInstance().getCount(DetachedCriteria.forClass(PublishedReport.class)
				.add(Restrictions.eq("orgi",orgi))
				.add(Restrictions.eq("name",name))
				.add(Restrictions.eq("reporttype",RivuDataContext.ReportTypeEnum.SAVEAS.toString()))
				.add(Restrictions.eq("tabtype",RivuDataContext.TabType.PRI.toString())),super.getUser(request));
    	/**
    	 * 保存报表
    	 */
    	if(count == 0){
	    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request) , orgi, reportid,true);
	    	if(name!=null){
	    		report.setId(UUID.randomUUID().toString());
	    		report.setName(name);
	    		report.setCreater(super.getUser(request).getId());
	    		report.setUserid(super.getUser(request).getId());
	    		report.setUsername(super.getUser(request).getUsername());
	    		report.setUseremail(super.getUser(request).getEmail());
	    		
	    		report.setCreatetime(new Date());
	    		report.setUpdatetime(new Date());
	    		report.setTabtype(RivuDataContext.TabType.PRI.toString());
	    		report.setReporttype(RivuDataContext.ReportTypeEnum.SAVEAS.toString());
	    		report.setTargetReport(reportid);
				report.setReportcontent(JSON.toJSONString(report.getReport())) ;
		    	ReportFactory.getReportInstance().createReport(report,super.getUser(request)) ;
		    	view.addObject("msg", LocalTools.getMessage("I_DESIGN_1000005")) ;
	    	}else{
	    		view.addObject("msg", LocalTools.getMessage("I_DESIGN_1000006")) ;
	    	}
    	}else{
    		view.addObject("msg", LocalTools.getMessage("I_DESIGN_1000007")) ;
    	}
    	return view ;
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/{modelid}/cleareport" , name="cleareport" , type="design",subtype="query")
    public ModelAndView cleareport(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @PathVariable String modelid ,@Valid String oid, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		reportModel.setExchangerw(false) ;
    		reportModel.setRowdimension("") ;
    		reportModel.setColdimension("") ;
    		reportModel.setMeasure("");
    		reportModel.setFilters(null);
    		reportModel.setColformatstr("");
    		reportModel.setRowformatstr("");
    		reportModel.setSortName(null);
    		reportModel.setSortType(null);
    		analyzerReport.setFilters(new ArrayList<ReportFilter>()) ;
    		reportModel.setDrilldown(new ArrayList<DrillDown>()) ;
    		reportModel.setWarning(new ArrayList<Warning>()) ;
    		/**
    		 * 去掉 除零操作，player页面，不应该改变除零操作
    		 */
//    		reportModel.setClearzero(false) ;
    		
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/{modelid}/deletecol" , name="deletecol" , type="design",subtype="query")
    public ModelAndView deletecol(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @PathVariable String modelid ,@Valid String title, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && title!=null && title.length()>0){
    		PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
			Cube cube = publishedCube.getCube() ;
			String[] titles = (title!=null ? title:"").split(",") ;
			if(reportModel.getMeasure()!=null){
				String[] measureids = reportModel.getMeasure().split(",") ;
				for(String tl : titles){
		    		for(CubeMeasure measure : cube.getMeasure()){
		    			if(tl.equals(measure.getName())){
		    				for(int i=0 ; i<measureids.length ; i++){
		    					String measureid = measureids[i] ;
		    					if(measureid!=null && measureid.equals(measure.getId())){
		    						measureids[i] = null ;
		    					}
		    				}
		    				break ;
		    			}
		    		}
				}
				StringBuffer strb = new StringBuffer();
				for(String measureid : measureids){
					if(measureid!=null){
						if(strb.length()>0){
							strb.append(",") ;
						}
						strb.append(measureid ) ;
					}
				}
				reportModel.setMeasure(strb.toString());
				
				/**
				 * 以下处理 数据表方式的删除列
				 */
				String levelid = "" ;
    			for(Dimension dimension : cube.getDimension()){
    				for(CubeLevel level : ("1".equals(dimension.getModeltype()) ? dimension.getDim() : dimension).getCubeLevel()){
    					if(level.getName().equals(title)){
    						levelid = level.getId() ;
    						break ;
    					}
    				}
    			}
    			strb = new StringBuffer();
    			if(reportModel.getRowdimension()!=null && reportModel.getRowdimension().length()>0 && reportModel.getRowdimension().indexOf(levelid)>=0){
    				for(String lvid : reportModel.getRowdimension().split(",")){
    					if(!levelid.equals(lvid)){
    						if(strb.length()>0){
    							strb.append(",") ;
    						}
    						strb.append(lvid) ;
    					}
    				}
    				reportModel.setRowdimension(strb.toString()) ;
    			}else if(reportModel.getColdimension()!=null && reportModel.getColdimension().length()>0 && reportModel.getColdimension().indexOf(levelid)>=0){
    				for(String lvid : reportModel.getColdimension().split(",")){
    					if(!levelid.equals(lvid)){
    						if(strb.length()>0){
    							strb.append(",") ;
    						}
    						strb.append(lvid) ;
    					}
    				}
    				reportModel.setColdimension(strb.toString()) ;
    			}
    			reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
    			/**
        		 * 去掉 除零操作
        		 */
        		reportModel.setClearzero(false) ;
			}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    
    @RequestMapping(value = "merge/{reportid}/{modelid}", name="cellmerge" , type="design",subtype="query")
	public ModelAndView cellmerge(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String start ,@Valid String end , @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
		String mergeType = request.getParameter("mt")!=null ? request.getParameter("mt") : "sum" ;
		if("1".equals(mergeType)){
			mergeType = "sum" ;
		}else if("2".equals(mergeType)){
			mergeType = "avg" ;
		}else if("5".equals(mergeType)){
			mergeType = "avgexp" ;
		}else if("3".equals(mergeType)){
			mergeType = "max" ;
		}else if("4".equals(mergeType)){
			mergeType = "min" ;
		}else{
			mergeType = "sum" ;
		}
		if(reportModel!=null){
			ReportCellMerge merge = new ReportCellMerge(start , end , mergeType);
	//		reportModel.setRowformatstr() ;
			merge.setFormat(request.getParameter("format")) ;//设置合并单元格格式
			merge.setId(String.valueOf(System.nanoTime())) ;
			if(reportModel.getRowformatstr()!=null && reportModel.getRowformatstr().length()>0){
				List<Object> rowFormatList = JSON.parseObject(reportModel.getRowformatstr(), List.class) ;
				boolean found = false ;
				for(Object cellFormat : rowFormatList){
					String type = BeanUtils.getProperty(cellFormat, "type") ;
					if(type!=null && type.equals("cellmerge")){
						ReportCellMerge temp = (ReportCellMerge) cellFormat;
						if(temp.getStart().equals(merge.getStart()) || temp.getEnd().equals(merge.getEnd())){
							found = true ;
							break ;
						}
					}
				}
				if(!found){
					rowFormatList.add(merge) ;
					reportModel.setRowformatstr(JSON.toJSONString(rowFormatList)) ;
				}
			}else{
				List<Object> rowFormatList = new ArrayList<Object>() ;
				rowFormatList.add(merge) ;
				reportModel.setRowformatstr(JSON.toJSONString(rowFormatList)) ;
			}
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "rmmerge/{reportid}/{modelid}", name="queryrmmerge" , type="design",subtype="query")
	public ModelAndView queryrmmerge(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String mergeid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && reportModel.getRowformatstr()!=null){
			List<Object> rowFormatList = JSON.parseObject(reportModel.getRowformatstr(), List.class) ;
			for(Object cellFormat : rowFormatList){
				String type = BeanUtils.getProperty(cellFormat, "type") ;
				if(type.equals("cellmerge")){
					ReportCellMerge temp = (ReportCellMerge) cellFormat;
					if(mergeid.equals(temp.getId())){
						rowFormatList.remove(cellFormat) ;
						reportModel.setRowformatstr(JSON.toJSONString(rowFormatList)) ;
						break ;
					}
				}
			}
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "rmdim/{reportid}/{modelid}", name="queryrmdim" , type="design",subtype="query")
    public ModelAndView queryrmdim(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @PathVariable String modelid ,@Valid String title, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && title!=null && title.length()>0){
    		PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
			Cube cube = publishedCube.getCube() ;
    		if((type==null || !type.equals("measure")) || !"cube".equals(cube.getDstype())){
    			String levelid = "" ;
    			for(Dimension dimension : cube.getDimension()){
    				for(CubeLevel level : ("1".equals(dimension.getModeltype()) ? dimension.getDim() : dimension).getCubeLevel()){
    					if(level.getName().equals(title)){
    						levelid = level.getId() ;
    						break ;
    					}
    				}
    			}
    			StringBuffer strb = new StringBuffer();
    			if(reportModel.getRowdimension()!=null && reportModel.getRowdimension().length()>0 && reportModel.getRowdimension().indexOf(levelid)>=0){
    				for(String lvid : reportModel.getRowdimension().split(",")){
    					if(!levelid.equals(lvid)){
    						if(strb.length()>0){
    							strb.append(",") ;
    						}
    						strb.append(lvid) ;
    					}
    				}
    				reportModel.setRowdimension(strb.toString()) ;
    			}else if(reportModel.getColdimension()!=null && reportModel.getColdimension().length()>0 && reportModel.getColdimension().indexOf(levelid)>=0){
    				for(String lvid : reportModel.getColdimension().split(",")){
    					if(!levelid.equals(lvid)){
    						if(strb.length()>0){
    							strb.append(",") ;
    						}
    						strb.append(lvid) ;
    					}
    				}
    				reportModel.setColdimension(strb.toString()) ;
    			}
    			/**
        		 * 去掉 除零操作
        		 */
        		reportModel.setClearzero(false) ;
    			reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
    		}
    		if(reportModel.getRowdimension()==null || reportModel.getRowdimension().length()==0){
				reportModel.setExchangerw(false) ;
			}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    /**
     * 删除新增的列
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "rmnewcol/{reportid}/{modelid}", name="queryrmnewcol" , type="design",subtype="query")
    public ModelAndView queryrmnewcol(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @PathVariable String modelid ,@Valid String id, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && id!=null && id.length()>0){
    		if(reportModel.getColformatstr()!=null){
    			List<Object> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			for(Object cellFormat : colList){
    				String celltype = BeanUtils.getProperty(cellFormat, "type") ;
    				if(celltype.equals("colrow")){
    					ReportCol temp = (ReportCol) cellFormat;
    					if(id.equals(temp.getId())){
    						colList.remove(cellFormat) ;
    						reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    						break ;
    					}
    				}
    			}
    		}
    		/**
    		 * 去掉 除零操作
    		 */
    		reportModel.setClearzero(false) ;
    		reportModel.setRowformatstr(null) ;
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    /**
     * 删除新增的列
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "rmnewrow/{reportid}/{modelid}", name="queryrmnewrow" , type="design",subtype="query")
    public ModelAndView queryrmnewrow(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @PathVariable String modelid ,@Valid String id, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && id!=null && id.length()>0){
    		if(reportModel.getColformatstr()!=null){
    			List<Object> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			for(Object cellFormat : colList){
    				String celltype = BeanUtils.getProperty(cellFormat, "type") ;
    				if(celltype.equals("rowcol")){
    					ReportCol temp = (ReportCol) cellFormat;
    					if(id.equals(temp.getId())){
    						colList.remove(cellFormat) ;
    						reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    						break ;
    					}
    				}
    			}
    		}
    		/**
    		 * 去掉 除零操作
    		 */
    		reportModel.setClearzero(false) ;
    		reportModel.setRowformatstr(null) ;
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
    }
    
    
    @RequestMapping(value = "newcol/{reportid}/{modelid}", name="querynewcol" , type="design",subtype="query")
	public ModelAndView querynewcol(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String exp, @PathVariable String modelid , @Valid ReportCol newCol) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		if(newCol==null){
    			newCol = new ReportCol("新建列");
        		newCol.setRowindex(-1);
//        		newCol.setExpress("A+B+C") ;
        		if(request.getParameter("exp")!=null && request.getParameter("exp").trim().length()>0){
        			String[] expparts = request.getParameter("exp").split(",") ;
        			StringBuffer strb = new StringBuffer() ;
        			for(String exppart : expparts){
        				if(exppart.trim().matches("[\\d]{1,}")){
        					if(strb.length()>0){
        						strb.append(" + ") ;
        					}
        					strb.append(RivuTools.getInx2Char(Integer.parseInt(exppart.trim()))) ;
        				}
        			}
        			newCol.setExpress(strb.toString()) ;
        		}
    		}

    		newCol.setId(String.valueOf(System.nanoTime())) ;
    		if(reportModel.getColformatstr()!=null && reportModel.getColformatstr().length()>0){
    			List<Object> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			colList.add(newCol) ;
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}else{
    			List<Object> colList = new ArrayList<Object>() ;
    			colList.add(newCol) ;
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}
    		reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "newrow/{reportid}/{modelid}", name="querynewrow" , type="design",subtype="query")
	public ModelAndView querynewrow(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String exp, @PathVariable String modelid , @Valid ReportCol newCol) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		newCol.setType("rowcol") ;	//新增行
    		newCol.setId(String.valueOf(System.nanoTime())) ;
    		if(reportModel.getColformatstr()!=null && reportModel.getColformatstr().length()>0){
    			List<Object> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			for (int i = 0; i < colList.size(); i++) {//同一个维度只添加一次会总行；，每次覆盖
    				String celltype = BeanUtils.getProperty(colList.get(i), "groupdim") ;
    				String group = BeanUtils.getProperty(colList.get(i), "group") ;
    				if(!Boolean.parseBoolean(group)&&!newCol.isGroup()){
    					colList.remove(i);
    					break;
    				}else{
    					if(Boolean.parseBoolean(group)&&newCol.isGroup()&&celltype!=null&&newCol.getGroupdim()!=null&&celltype.equals(newCol.getGroupdim())){
    						colList.remove(i);
    						break;
    					}
    				}
				}
    			colList.add(newCol) ;
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}else{
    			List<Object> colList = new ArrayList<Object>() ;
    			colList.add(newCol) ;
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}
    		reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "newroweditdo/{reportid}/{modelid}", name="newroweditdo" , type="design",subtype="query")
	public ModelAndView newroweditdo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String exp, @PathVariable String modelid , @Valid ReportCol newCol) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		newCol.setType("rowcol") ;	//新增行
    		newCol.setId(String.valueOf(System.nanoTime())) ;
    		if(reportModel.getColformatstr()!=null && reportModel.getColformatstr().length()>0){
    			List<ReportCol> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			for(ReportCol col : colList){
    				if(col.getId().equals(newCol.getId())){
    					BeanUtils.copyProperties(col, newCol) ;
    				}
    			}
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}else{
    			List<Object> colList = new ArrayList<Object>() ;
    			colList.add(newCol) ;
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}
    		reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "exchange/{reportid}/{modelid}", name="queryexchange" , type="design",subtype="query")
	public ModelAndView queryexchange(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
//    		String rowdim = reportModel.getRowdimension() ;
//    		reportModel.setRowdimension(reportModel.getColdimension()) ;
//    		reportModel.setColdimension(rowdim);
    		if(reportModel.getRowdimension().length()>0 || reportModel.getRowdimension().replaceAll(",", "").length()>0){
    			if(reportModel.isExchangerw()){
    				view.addObject("exchange", LocalTools.getMessage("I_REPORT_10000101")) ;
    			}else{
    				view.addObject("exchange", LocalTools.getMessage("I_REPORT_10000102")) ;
    			}
    			reportModel.setExchangerw(reportModel.isExchangerw() ? false : true) ;
    		}else{
    			reportModel.setExchangerw(false) ;
    			view.addObject("exchange", LocalTools.getMessage("E_REPORT_10000102")) ;
    		}
     		reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "addsumcol/{reportid}/{modelid}", name="queryaddsumcol" , type="design",subtype="query")
	public ModelAndView queryaddsumcol(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/addsumcol") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	view = createModelAndView(view , true , report , request , reportModel);
    	if(view.getModelMap().get("reportData")!=null){
    		ReportData reportData = (ReportData) view.getModelMap().get("reportData") ;
    		if(reportData.getRow()!=null){
    			view.addObject("coltitle", reportData.getRow().getFirstTitle()) ;
    		}
			if(reportData.getCol()!=null && reportData.getCol().getFirstTitle()!=null){
				view.addObject("rowtitle", reportData.getCol().getFirstTitle()) ;
			}
    	}
    	return view;
	}
    /**
     * 新增列
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "addsumrow/{reportid}/{modelid}", name="queryaddsumrow" , type="design",subtype="query")
	public ModelAndView queryaddsumrow(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/addsumrow") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	view = createModelAndView(view , true , report , request , reportModel);
    	if(view.getModelMap().get("reportData")!=null){
    		ReportData reportData = (ReportData) view.getModelMap().get("reportData") ;
    		if(reportData.getRow()!=null){
    			view.addObject("coltitle", reportData.getRow().getFirstTitle()) ;
    		}
			if(reportData.getCol()!=null && reportData.getCol().getFirstTitle()!=null){
				view.addObject("rowtitle", reportData.getCol().getFirstTitle()) ;
			}
    	}
    	return view;
	}
    

    @RequestMapping(value = "editsumcol/{reportid}/{modelid}", name="editsumcol" , type="design",subtype="query")
	public ModelAndView editsumcol(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String  dataid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/editsumcol") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		ReportCol reportCol = null ; 
    		if(reportModel.getColformatstr()!=null){
    			List<Object> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			for(Object cellFormat : colList){
    				String celltype = BeanUtils.getProperty(cellFormat, "type") ;
    				ReportCol temp = (ReportCol) cellFormat;
					if(dataid.equals(temp.getId())){
						reportCol = temp ;
						if(celltype.equals("rowcol")){
							view = request(super.createManageResponse("/pages/design/player/editsumrow") , orgi) ;
	    				}
						break ;
					}
    			}
    		}
    		view.addObject("data", reportCol) ;
    		view.addObject("reportModel", reportModel) ;
    		view.addObject("report", report) ;
    		
    		view = createModelAndView(view , true , report , request , reportModel);
        	if(view.getModelMap().get("reportData")!=null){
        		ReportData reportData = (ReportData) view.getModelMap().get("reportData") ;
        		if(reportData.getRow()!=null && reportData.getRow().getFirstTitle()!=null&&reportData.getRow().getFirstTitle().size()>0){
        			view.addObject("coltitle", reportData.getRow().getFirstTitle()) ;
        		}
    			if(reportData.getCol()!=null && reportData.getCol().getFirstTitle()!=null){
    				view.addObject("rowtitle", reportData.getCol().getFirstTitle()) ;
    			}
        	}
		}
    	
		return view;
	}
    
    
    @RequestMapping(value = "editnewcoldo/{reportid}/{modelid}", name="editnewcoldo" , type="design",subtype="query")
	public ModelAndView editnewcoldo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @Valid String exp, @PathVariable String modelid , @Valid ReportCol newCol) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		newCol.setType("colrow") ;	//新增列
    		if(reportModel.getColformatstr()!=null && reportModel.getColformatstr().length()>0){
    			List<ReportCol> colList = JSON.parseObject(reportModel.getColformatstr(), List.class) ;
    			for(ReportCol newcol : colList){
    				if(newcol.getId().equals(newCol.getId())){
    					BeanUtils.copyProperties(newcol, newCol) ;
    					break;
    				}
    			}
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}else{
    			List<Object> colList = new ArrayList<Object>() ;
    			colList.add(newCol) ;
    			reportModel.setColformatstr(JSON.toJSONString(colList)) ;
    		}
    		reportModel.setRowformatstr(null) ;	//增加和修改 col 需要 去掉单元格合并
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    /**
     * 表格转图片
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/chart/{reportid}/{modelid}", name="table2chart" , type="design",subtype="query")
	public ModelAndView table2chart(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/charts") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	view = createModelAndView(view , true , report , request , reportModel);
    	List<TypeCategory> catagoryList = super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class)
				.addOrder(Order.asc("createtime"))
				.add(Restrictions.eq("ctype", "chart")));
    	view.addObject("catagoryList",catagoryList);
    	if(catagoryList.size()>0){
    		view.addObject("templetList",super.getService().findAllByCriteria(DetachedCriteria.forClass(SearchResultTemplet.class)
				.addOrder(Order.asc("createtime"))
				.add(Restrictions.eq("templettype", "chart"))
				.add(Restrictions.eq("typeid", catagoryList.get(0).getId()))));
    		view.addObject("catagory",catagoryList.get(0));
    	}
    	view.addObject("reportid",reportid);
    	view.addObject("modelid",modelid);
    	
    	return view;
	}
    
    @RequestMapping(value = "/chart/templetlist/{catagoryid}", name="templetlist" , type="design",subtype="query")
	public ModelAndView templetlist(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String catagoryid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/templetlist") , orgi) ;
    	
		view.addObject("templetList",super.getService().findAllByCriteria(DetachedCriteria.forClass(SearchResultTemplet.class)
			.addOrder(Order.asc("createtime"))
			.add(Restrictions.eq("templettype", "chart"))
			.add(Restrictions.eq("typeid", catagoryid))));
    	
    	view.addObject("catagory",super.getService().getIObjectByPK(TypeCategory.class, catagoryid));
    	return view;
	}
    
    /**
     * 表格转图片
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "exviewtype/{reportid}/{modelid}", name="exviewtype" , type="design",subtype="query")
	public ModelAndView exviewtype(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		reportModel.setViewtype("view") ;
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    /**
     * 表格转图表
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "exchartype", name="exchartype" , type="design",subtype="query")
	public ModelAndView exchartype(HttpServletRequest request , @PathVariable String  orgi , @Valid String  reportid, @Valid String modelid, @Valid String templetid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		reportModel.setViewtype("chart") ;
    		reportModel.setChartemplet(templetid);
		}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    /**
     * 表格转图片
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "setstyle/{reportid}/{modelid}", name="setstyle" , type="design",subtype="query")
	public ModelAndView setstyle(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid , @Valid String datatype , @Valid String dataid , @Valid String key , @Valid String value , @Valid String pline) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && !StringUtils.isEmpty(key)){
    		List<StyleBean> styleBeanList = null ;
    		StyleBean styleBean = null ;
    		boolean found = false;
    		if(reportModel.getStylestr()!=null && !"clear".equals(key)){
    			styleBeanList = JSON.parseArray(reportModel.getStylestr(),StyleBean.class) ;
    			for(int i =0 ; i< styleBeanList.size() ; ){
    				styleBean = styleBeanList.get(i) ;
    				if(styleBean.getType().equals("model") && styleBean.getDataid()!=null && dataid.equals(styleBean.getDataid())){
    					if("%".equals(pline)){
    						reportModel.setStyle(styleBean) ;
    					}else if("0".equals(pline)){
    						reportModel.setEvenstyle(styleBean) ;
    					}else if("1".equals(pline)){
    						reportModel.setOddstyle(styleBean) ;
    					}
					}
    				if(styleBean.getDataid()!=null && dataid.equals(styleBean.getDataid()) && (pline!=null && pline.equals(styleBean.getPline()))){
    					found = true ;
    					if(value!=null && value.equals(BeanUtils.getProperty(styleBean, key))){
							BeanUtils.setProperty(styleBean, key , null) ;
						}else{
							BeanUtils.setProperty(styleBean, key , value) ;
						}
    					break ;
    				}
    				if(styleBean.getType()==null || styleBean.getPline()==null){
						styleBeanList.remove(i) ;
						continue ;
					}
    				i++ ;
    			}
    		}
    		if(!found){
    			if(styleBeanList == null){
    				styleBeanList = new ArrayList<StyleBean>();
    			}
    			if(!"clear".equals(key)){
	    			styleBean = new StyleBean() ;
	    			styleBean.setDataid(dataid) ;
	    			styleBean.setPline(pline) ;
	    			styleBean.setType(datatype) ;
	    			BeanUtils.setProperty(styleBean, key , value) ;
	    			styleBeanList.add(styleBean) ;
	    			if(styleBean.getType().equals("model")){
	    				if("%".equals(pline)){
							reportModel.setStyle(styleBean) ;
						}else if("0".equals(pline)){
							reportModel.setEvenstyle(styleBean) ;
						}else if("1".equals(pline)){
							reportModel.setOddstyle(styleBean) ;
						}
					}
    			}
    		}
    		if(styleBean!=null && "margin".equals(key)){
    			if(datatype.equals("model")){
    				BeanUtils.setProperty(styleBean, "margin" , value.equals("left") ? "0" : value.equals("center") ? "0 auto" : "0 0 0 auto" ) ;
    				BeanUtils.setProperty(styleBean, "textalign" , null ) ;
    			}else{
    				BeanUtils.setProperty(styleBean, "margin" , null) ;
    				BeanUtils.setProperty(styleBean, "textalign" , value) ;
    			}
    		}
    		if("clear".equals(key)){
    			styleBeanList.clear();
    			reportModel.setStyle(null) ;
    			reportModel.setOddstyle(null) ;
    			reportModel.setEvenstyle(null) ;
    		}
    		reportModel.setStylestr(JSON.toJSONString(styleBeanList)) ;
    	}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    /**
     * 表格转图表
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "drilldef/{reportid}/{modelid}", name="querydrildef" , type="design",subtype="query")
	public ModelAndView querydrildef(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid , @Valid String title) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/querydrildef") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		
    		for(int i=0 ; i<  reportModel.getDrilldown().size() ; i++){
    			DrillDown drillDown = reportModel.getDrilldown().get(i) ;
    			if(title.equals(drillDown.getDataname())){
    				view.addObject("drill", drillDown) ;
    				break ;
    			}
    		}
    		
    		view.addObject("reportModel", reportModel) ;
    		view.addObject("type", request.getParameter("type")) ;
    		view.addObject("report", report) ;
    		view.addObject("col", title) ;
    		view.addObject("reportDicList", ReportFactory.getReportInstance().getReportDicList(orgi, super.getUser(request), "0", RivuDataContext.TabType.PUB.toString())) ;
    		view.addObject("reportList", ReportFactory.getReportInstance().getReportList("0", orgi, super.getUser(request), RivuDataContext.TabType.PUB.toString(), RivuDataContext.ReportTypeEnum.REPORT.toString())) ;
		}
		return view ;
	}
    

    /**
     * 表格转图表
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "loadreport/{dicid}", name="loadreport" , type="design",subtype="query")
	public ModelAndView loadreport(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  dicid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/loadreport") , orgi) ;
    	view.addObject("reportList", ReportFactory.getReportInstance().getReportList(dicid, orgi, super.getUser(request), RivuDataContext.TabType.PUB.toString(), RivuDataContext.ReportTypeEnum.REPORT.toString())) ;
		return view ;
	}
    
    /**
     * 表格转图表
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "drilldefdo/{reportid}/{modelid}", name="querydrilldefdo" , type="design",subtype="query")
	public ModelAndView querydrilldefdo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String modelid , @Valid DrillDown data) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		boolean found = false ;
    		data.setId(String.valueOf(System.currentTimeMillis())) ;
    		for(int i=0 ; i<  reportModel.getDrilldown().size() ; i++){
    			DrillDown drillDown = reportModel.getDrilldown().get(i) ;
    			if(data.getDataname()!=null && data.getDataname().equals(drillDown.getDataname())){
    				found = true ;
    				reportModel.getDrilldown().set(i , data) ;
    				break ;
    			}
    		}
    		if(!found){
    			reportModel.getDrilldown().add(data) ;
    		}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "/filterparamadd/{reportid}/{modelid}", name="filterparamadd" , type="design",subtype="query")
	public ModelAndView filterparamadd(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid , @Valid String name , @Valid String levelid , @Valid String dimid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/filteradd") , orgi) ;
    	view.addObject("reportid",reportid);
    	view.addObject("modelid",modelid);
    	
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
       	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
	    List<ReportFilter> filters = new ArrayList<ReportFilter>();
       	
       	for(int i=0 ; i < analyzerReport.getFilters().size() ; i++){
       		ReportFilter filter = analyzerReport.getFilters().get(i) ;
   			if(filter.getDimid().equals(dimid)){
   				filters.add(filter);
   			}
       	}
       	view.addObject("filters", filters) ;
       	view.addObject("groups", reportModel.getGroupList()) ;
    	if(name!=null && levelid!=null){
    		view.addObject("name",name);
    		view.addObject("levelid",levelid);
    		view.addObject("dimid",dimid);
    	}
    	return view;
	}
    
    @RequestMapping(value = "/filteradd/{reportid}/{modelid}/{name}/{levelid}", name="filteradd" , type="design",subtype="query")
	public ModelAndView filteradd(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid,@PathVariable String  name,@PathVariable String  levelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/filterlist") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
	    
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	/**
    	 * 添加过滤器
    	 */
    	boolean exist = false ;
    	if(reportModel != null){
    		for(ReportFilter reportFilter : RivuTools.getRequestFilters(analyzerReport.getFilters())){
    			if(reportFilter.getDataid().equals(levelid)){
    				exist = true ;
    				break ;
    			}
    		}
    		if(!exist){
	    		ReportFilter filter = new ReportFilter();
	    		filter.setId(String.valueOf(System.currentTimeMillis()) );
	    		filter.setName(name) ;
	    		filter.setDataid(levelid) ;
	    		filter.setModelid(modelid) ;
	    		if("select".equals(filter.getModeltype())){
       				filter.setValuefiltertype(RivuDataContext.ReportCompareEnum.COMPARE.toString()) ;
       			}
       			if(RivuDataContext.FilterModelType.DATE.toString().equals( filter.getModeltype()) || RivuDataContext.FilterModelType.DATE.toString().equals( filter.getModeltype())){
	    			filter.setConvalue(RivuDataContext.FilterConValueType.INPUT.toString());
	    		}
	    		
	    		filter.setFuntype(RivuDataContext.FilteFunType.FILTER.toString());
	    		filter.setFiltertype(RivuDataContext.FilterEnum.REPORT.toString()) ;
	    		filter.setContype(RivuDataContext.FilterConType.DIMENSION.toString()) ;
	        	filter.setCode(filter.getId());
	        	filter.setModeltype("text");
	        	filter.setConvalue(RivuDataContext.FilterConValueEnum.INPUT.toString());
	        	filter.setValuefiltertype("compare");
	        	filter.setComparetype("equal");
	        	filter.setDefaultvalue("");
	        	filter.setFilterprefix("");
	        	filter.setFiltersuffix("") ;
	        	
	        	if(reportModel.getPublishedcubeid()!=null && reportModel.getPublishedcubeid().length()>0){
	    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
	    			Cube cube = publishedCube.getCube() ;
	    			boolean find = false ;
	    			for(Dimension dim : cube.getDimension()){
						for(CubeLevel level : dim.getCubeLevel()){
							if(filter.getDataid().equals(level.getId())){
								filter.setDataname(dim.getName()) ;
								filter.setDimid(dim.getId()) ;
								filter.setContype(RivuDataContext.FilterConType.DIMENSION.toString()) ;
								find = true ;
								break ;
							}
						}
					}
	    			/**
	    			 * 暂不支持 指标过滤
	    			 */
//	    			if(!find){
//	    				for(CubeMeasure measure : cube.getMeasure()){
//	    					if(measure.getId().equals(filter.getDataid())){
//	    						
//	    					}
//	    				}
//	    			}
	    			
				}
	        	
	        	analyzerReport.getFilters().add(filter);
    		}
    	}
    	
    	if(!exist){
	    	/**
	    	 * 更新缓存
	    	 */
	    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	}else{
    		view.addObject("ation_message", LocalTools.getMessage("E_DESIGN_10010001")) ;
    	}
    	
    	return createModelAndView(view , report , request , reportModel , false ,false);
	}
    
	@RequestMapping(value = "/axisset/{reportid}/{modelid}", name="axisset" , type="design",subtype="query")
	public ModelAndView axisset(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/axisset") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
	    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel != null){
    		view.addObject("newCol", JSON.parseObject(reportModel.getColformatstr() , List.class)) ;
    	}
    	return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "/{reportid}/{modelid}/filteraddo", name="filteraddo" , type="design",subtype="query")
	public ModelAndView filteraddo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid,@Valid ReportFilter filter) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/filterlist") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	boolean exist = false ;
    	if(reportModel != null){
    		for(ReportFilter reportFilter : RivuTools.getRequestFilters(analyzerReport.getFilters())){
    			if(reportFilter.getDataid().equals(filter.getDataid())){
    				exist = true ;
    				break ;
    			}
    		}
    		if(!exist){
		    	filter.setId(String.valueOf(System.currentTimeMillis()) );
		    	filter.setCode(filter.getId());
		    	filter.setModelid(modelid) ;
		    	
		    	if(reportModel.getPublishedcubeid()!=null && reportModel.getPublishedcubeid().length()>0){
					PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
					Cube cube = publishedCube.getCube() ;
					
					for(Dimension dim : cube.getDimension()){
						for(CubeLevel level : dim.getCubeLevel()){
							if(filter.getDataid().equals(level.getId())){
								filter.setDataname(dim.getName()) ;
								filter.setDimid(dim.getId()) ;
								break ;
							}
						}
					}
				}
		    	analyzerReport.getFilters().add(filter);
    		}
    	}
    	if(!exist){
	    	/**
	    	 * 更新缓存
	    	 */
	    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	}else{
    		view.addObject("ation_message", LocalTools.getMessage("E_DESIGN_10010001")) ;
    	}
    	
		return createModelAndView(view , report , request , reportModel , false ,false);
	}
    @RequestMapping(value = "/filterdelo/{reportid}/{modelid}/{filterid}", name="filterdelo" , type="design",subtype="query")
	public ModelAndView filterdelo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String filterid,@PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/filterlist") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
       	if(reportModel != null){
	    	List<ReportFilter> filters = analyzerReport.getFilters();
	    	for (int i = 0; i < filters.size(); i++) {
	    		ReportFilter filter = filters.get(i);
	    		if(filter.getId().equals(filterid)){
	    			filters.remove(i) ;
	    			break ;
	    		}
			}
       	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
   		return createModelAndView(view , report , request , null, false ,false);
	}
    
    @RequestMapping(value = "savefiltervalues/{reportid}/{modelid}", name="savefiltervalues" , type="design",subtype="custom")
   	public ModelAndView savefiltervalues(HttpServletRequest request , @PathVariable String  orgi ,  @PathVariable String  reportid, @PathVariable String  modelid,@Valid ReportFilter filter) throws Exception{
       	ModelAndView view = request(super.createManageResponse("/pages/public/success") , orgi) ;
       	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
       	int ps = request.getParameter("ps") != null && !"".equals(request.getParameter("ps")) ? Integer.parseInt(request.getParameter("ps")):20;
       	AnalyzerReport analyzerReport = report.getReport() ;
       	AnalyzerReportModel reportModel = null ;
       	if(analyzerReport.getModel().size()>0){
       		for(AnalyzerReportModel model : analyzerReport.getModel()){
       			if(model.getId().equals(modelid)){
       				reportModel = model ;
       				model.setPageSize(ps);
       				break;
       			}
       		}
       	}
       	if(reportModel != null){
       		
   	    	/**
   	    	 * 以下代码用于
   	    	 */
   	    	for(ReportFilter reportFilter : analyzerReport.getFilters()){
   	    		if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype())){
   	    			if(request.getParameter(reportFilter.getCode()+"_start")!=null && request.getParameter(reportFilter.getCode()+"_end")!=null){
   		    			if(RivuDataContext.FilterConValueEnum.AUTO.toString().equals(reportFilter.getConvalue())){
   		    				String start = request.getParameter(reportFilter.getCode()+"_start")!=null ? request.getParameter(reportFilter.getCode()+"_start") : "" ;
   		    				String end = request.getParameter(reportFilter.getCode()+"_end")!=null ? request.getParameter(reportFilter.getCode()+"_end") : "" ;
//   		    				if((start.length() - start.replaceAll(".", "").length()) != (end.length() - end.replaceAll(".", "").length())){
//   		    					continue ;
//   		    				}
   		    			}
   		    			reportFilter.setRequeststartvalue(request.getParameter(reportFilter.getCode()+"_start")) ;
   		    			reportFilter.setRequestendvalue(request.getParameter(reportFilter.getCode()+"_end")) ;
   	    			}
   	    		}else{
   		    		if(request.getParameter(reportFilter.getCode())!=null){
   		    			reportFilter.setRequestvalue(request.getParameter(reportFilter.getCode())) ;
   		    		}
   	    		}
   	    	}
       	}
       	/**
       	 * 更新缓存
       	 */
       	updateCacheReport(request , report , analyzerReport , orgi , false) ;
       	
   		return view;
   	}
    
    @RequestMapping(value = "/{reportid}/{modelid}/resetFilter", name="resetFilter" , type="design",subtype="custom")
   	public ModelAndView resetFilter(HttpServletRequest request , @PathVariable String  orgi ,  @PathVariable String  reportid, @PathVariable String  modelid) throws Exception{
       	ModelAndView view = request(super.createManageResponse("/pages/design/player/filterlist") , orgi) ;
       	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
       	AnalyzerReport analyzerReport = report.getReport() ;
       	AnalyzerReportModel reportModel = null ;
       	if(analyzerReport.getModel().size()>0){
       		for(AnalyzerReportModel model : analyzerReport.getModel()){
       			if(model.getId().equals(modelid)){
       				reportModel = model ;
       				break;
       			}
       		}
       	}
       	if(reportModel != null){
   	    	/**
   	    	 * 以下代码用于
   	    	 */
   	    	for(ReportFilter reportFilter : analyzerReport.getFilters()){
   	    		if(!reportFilter.isRequest()){
   	    			if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype())){
   	   	    			reportFilter.setRequeststartvalue(null) ;
   	   	    			reportFilter.setRequestendvalue(null) ;
   	   	    		}else{
   	   		    		reportFilter.setRequestvalue(null) ;
   	   	    		}
   	    		}
   	    		
   	    	}
       	}
       	/**
       	 * 更新缓存
       	 */
       	updateCacheReport(request , report , analyzerReport , orgi , false) ;
       	
   		return createModelAndView(view , false , report , request , reportModel);
   	}
    
    @RequestMapping(value = "/{reportid}/{modelid}/queryFilter", name="queryFilter" , type="design",subtype="query")
	public ModelAndView queryFilter(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String  modelid,@Valid ReportFilter filter) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	super.processRequestParam(analyzerReport, request , true) ;
    	view.addObject("loadata", true) ;
    	if(reportModel != null){
    		
    		if(request.getParameter("sortType")!=null&&request.getParameter("sortName")!=null){
    			reportModel.setSortName(request.getParameter("sortName"));
    			reportModel.setSortType(request.getParameter("sortType"));
    			reportModel.setSortstr(request.getParameter("sortType"));
    			
    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
    			Cube cube = publishedCube.getCube() ;
    				
    			for(Dimension dim : cube.getDimension()){
					Iterator<CubeLevel> leveles = dim.getCubeLevel().iterator();

					boolean found = false;
					while (leveles.hasNext()) {
						CubeLevel level = leveles.next();
						if(level.getName().equals(reportModel.getSortName())){
							reportModel.setSortstr(level.getCode());
						}
					}
				}
    			for(CubeMeasure mea : cube.getMeasure()){
					if(mea.getName().equals(reportModel.getSortName())){
						reportModel.setSortstr(mea.getCode());
					}
					
				}
    		}
	    	/**
	    	 * 以下代码用于
	    	 */
	    	for(ReportFilter reportFilter : RivuTools.getRequestFilters(analyzerReport.getFilters())){
	    		if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype())){
	    			if(request.getParameter(reportFilter.getCode()+"_start")!=null && request.getParameter(reportFilter.getCode()+"_end")!=null){
		    			if(RivuDataContext.FilterConValueEnum.AUTO.toString().equals(reportFilter.getConvalue())){
		    				String start = request.getParameter(reportFilter.getCode()+"_start")!=null ? request.getParameter(reportFilter.getCode()+"_start") : "" ;
		    				String end = request.getParameter(reportFilter.getCode()+"_end")!=null ? request.getParameter(reportFilter.getCode()+"_end") : "" ;
		    				if((start.length() - start.replaceAll(".", "").length()) != (end.length() - end.replaceAll(".", "").length())){
		    					continue ;
		    				}
		    			}
		    			reportFilter.setRequeststartvalue(request.getParameter(reportFilter.getCode()+"_start")) ;
		    			reportFilter.setRequestendvalue(request.getParameter(reportFilter.getCode()+"_end")) ;
	    			}
	    		}else{
		    		if(request.getParameter(reportFilter.getCode())!=null){
		    			reportFilter.setRequestvalue(request.getParameter(reportFilter.getCode())) ;
		    		}
	    		}
	    	}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    @RequestMapping(value = "/{reportid}/clearFilter", name="clearFilter" , type="design",subtype="query")
   	public ModelAndView clearFilter(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid) throws Exception{
       	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
       	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
       	AnalyzerReport analyzerReport = report.getReport() ;
       	for(int i=0 ; i < analyzerReport.getFilters().size() ;){
       		ReportFilter filter = analyzerReport.getFilters().get(i) ;
       		if(!filter.isRequest()&&(filter.getFuntype()==null || RivuDataContext.FilteFunType.FILTER.toString().equals(filter.getFuntype()))){
       			analyzerReport.getFilters().remove(i) ;
       		}else{
       			i++;
       		}
       	}
       	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
   		return createModelAndView(view , report , request , null, false ,true);
   	}
    /**
     * 修改过滤器
     * @param request
     * @param orgi
     * @param reportid
     * @param name
     * @param levelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{reportid}/{modelid}/editFilter/{filterid}", name="editFilter" , type="design",subtype="query")
	public ModelAndView editFilter(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String  modelid,@PathVariable String  filterid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/filteredit") , orgi) ;
    	view.addObject("reportid",reportid);
    	view.addObject("modelid",modelid);
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
       	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
       	List<ReportFilter> filters = new ArrayList<ReportFilter>();
       	ReportFilter cur_filter = null;
       	for(int i=0 ; i < analyzerReport.getFilters().size() ; i++){
       		ReportFilter filter = analyzerReport.getFilters().get(i) ;
       		if(filterid!=null && filterid.equals(filter.getId())){
       			filter.setQuery(filterQueryText(analyzerReport, null, request, true, filter));
       			cur_filter = filter ;
       			break;
       		}
       	}
       	for(int i=0 ; i < analyzerReport.getFilters().size() ; i++){
       		ReportFilter filter = analyzerReport.getFilters().get(i) ;
       		if(filterid!=null && !filterid.equals(filter.getId()) && filter.getDimid().equals(cur_filter.getDimid())){
       			filters.add(filter);
       		}
       	}
       	view.addObject("filter", cur_filter) ;
       	view.addObject("filters", filters) ;
       	view.addObject("groups", reportModel.getGroupList()) ;
    	return view;
	}
    
    /**
     * 级联加载下级数据
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @param filterid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{reportid}/{modelid}/{filterid}/loadfiltervalues", name="loadfiltervalues" , type="design",subtype="custom")
	public ModelAndView loadfiltervalues(HttpServletRequest request , @PathVariable String  orgi ,  @PathVariable String  reportid, @PathVariable String  modelid,@PathVariable String  filterid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/loadfiltervalues") , orgi) ;
    
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
       	AnalyzerReport analyzerReport = report.getReport() ;
       	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
       	for(int i=0 ; i < analyzerReport.getFilters().size() ; i++){
       		ReportFilter filter = analyzerReport.getFilters().get(i) ;
       		ReportFilter parentFilter = null;
       		if(request.getParameter("parentid")!=null && request.getParameter("parentid").toString().equals(filter.getId())){
       			parentFilter = filter;
       			parentFilter.setRequestvalue(request.getParameter("parentvalue").toString());
       			updateCacheReport(request , report , analyzerReport , orgi) ;
       		}
       		if(filterid!=null && filterid.equals(filter.getId())){
       			filter.setRequestvalue(null);
       			if("select".equals(filter.getModeltype()))
       				updateCacheReport(request , report , analyzerReport , orgi) ;
       			parentFilter = new ReportFilter();
       			parentFilter.setId(request.getParameter("parentid"));
       			filter.setParentFilter(parentFilter);
       			filter.setParentValue(request.getParameter("parentvalue"));
       			fillFilterValue(analyzerReport ,report.isCache() , reportModel, filter, request, false);
       			view.addObject("filter", filter) ;
       			break;
       		}
       	}
       	PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
		if(publishedCube!=null){
			Cube cube = publishedCube.getCube() ;
			view.addObject("cube", cube) ;
		}
    	return view;
	}
    
    @RequestMapping(value = "/{reportid}/{modelid}/filtereditdo", name="filtereditdo" , type="design",subtype="query")
	public ModelAndView filtereditdo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid, @PathVariable String  modelid,@Valid ReportFilter filter) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/filterlist") , orgi) ;
    	
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel != null){
    		for(int i=0 ; i < analyzerReport.getFilters().size() ; i++){
           		ReportFilter tempFilter = analyzerReport.getFilters().get(i) ;
           		if(tempFilter.getId().equals(filter.getId())){
           			filter.setFiltertype(RivuDataContext.FilterEnum.REPORT.toString()) ;
           			filter.setFuntype(RivuDataContext.FilteFunType.FILTER.toString()) ;
           			filter.setModelid(modelid) ;
           			filter.setQueryText(tempFilter.getQueryText());
           			filter.setGroupids(tempFilter.getGroupids());
           			if("select".equals(filter.getModeltype())){
           				filter.setValuefiltertype(RivuDataContext.ReportCompareEnum.COMPARE.toString()) ;
           			}
           			if(RivuDataContext.FilterModelType.DATE.toString().equals( filter.getModeltype()) || RivuDataContext.FilterModelType.DATE.toString().equals( filter.getModeltype())){
    	    			filter.setConvalue(RivuDataContext.FilterConValueType.INPUT.toString());
    	    		}
           			filter.setRequeststartvalue(null) ;
           			filter.setRequestendvalue(null) ;
           			filter.setRequestvalue(null) ;
           			if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(tempFilter.getValuefiltertype())){
           				filter.setDefaultvalue("") ;
           			}
           			
           			if(reportModel.getPublishedcubeid()!=null && reportModel.getPublishedcubeid().length()>0){
        				PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
        				Cube cube = publishedCube.getCube() ;
        				view.addObject("cube", cube) ;
        				for(Dimension dim : cube.getDimension()){
        					for(CubeLevel level : dim.getCubeLevel()){
        						if(filter.getDataid().equals(level.getId())){
        							filter.setDataname(dim.getName()) ;
        							filter.setDimid(dim.getId()) ;
        							break ;
        						}
        					}
        				}
        			}
           			analyzerReport.getFilters().set(i, filter) ;
           			break ;
           		}
           	}
    	}
    	
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , null ,false ,false);
	}
    
    
    @RequestMapping(value = "/warning/{reportid}/{modelid}", name="warning" , type="design",subtype="query")
   	public ModelAndView warning(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid , @Valid String name) throws Exception{
       	ModelAndView view = request(super.createManageResponse("/pages/design/player/warning") , orgi) ;
       	view.addObject("reportid",reportid);
       	view.addObject("modelid",modelid);
       	if(name!=null){
       		view.addObject("name",name);
       	}
       	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel != null){
    		view.addObject("warningList",reportModel.getWarning());
    		view.addObject("reportModel",reportModel);
    		if(reportModel.getPublishedcubeid()!=null && reportModel.getPublishedcubeid().length()>0){
    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
    			Cube cube = publishedCube.getCube() ;
    			view.addObject("cube", cube) ;
			}
    	}
       	return view;
   	}
    
    @RequestMapping(value = "/warningaddo/{reportid}/{modelid}", name="warningaddo" , type="design",subtype="query")
   	public ModelAndView warningaddo(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid , @Valid String dataname , @Valid Warning warning) throws Exception{
       	ModelAndView view = request(super.createManageResponse("/pages/design/player/warning") , orgi) ;
       	view.addObject("reportid",reportid);
       	view.addObject("modelid",modelid);
       	if(dataname!=null){
       		view.addObject("name",dataname);
       	}
       	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel != null){
    		warning.setId(String.valueOf(System.currentTimeMillis())) ;
    		reportModel.getWarning().add(warning) ;
    		view.addObject("warningList",reportModel.getWarning());
    		view.addObject("reportModel",reportModel);
    		if(reportModel.getPublishedcubeid()!=null && reportModel.getPublishedcubeid().length()>0){
    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(reportModel.getPublishedcubeid()) ;
    			Cube cube = publishedCube.getCube() ;
    			view.addObject("cube", cube) ;
			}
    		/**
        	 * 更新缓存
        	 */
        	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	}
       	return view;
   	}
    
    @RequestMapping(value = "/{reportid}/updatecache", name="updatecache" , type="design",subtype="query")
	public ModelAndView updatecache(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@Valid ReportFilter filter) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(request.getParameter("modelid"))){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		
    	}
		return createModelAndView(view , report , null, request , true , reportModel  , false , true ,true);
	}
    /**
     * 加载模式
     * @param request
     * @param orgi
     * @param reportid
     * @param filterid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "chartproperties/{reportid}/{modelid}", name="chartproperties" , type="design",subtype="query")
	public ModelAndView chartproperties(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/chartproperties") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		view.addObject("reportModel", reportModel) ;
    		view.addObject("report", report) ;
		}
	
    	return view;
	}
    
    /**
     * 除零操作
     * @param request
     * @param orgi
     * @param reportid
     * @param filterid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "clearzero/{reportid}/{modelid}", name="clearzero" , type="design",subtype="query")
	public ModelAndView clearzero(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		if(reportModel.isClearzero()){
    			reportModel.setClearzero(false) ;
    		}else{
    			reportModel.setClearzero(true) ;
    		}
		}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	
		return createModelAndView(view , report , request , reportModel , false ,true);
	}
    
    
    /**
     * 保存图表模式
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "savechartproperties/{reportid}/{modelid}", name="savechartproperties" , type="design",subtype="query")
	public ModelAndView savechartproperties(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid,@Valid AnalyzerReportModel data) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		reportModel.setWidth(data.getWidth()) ;
    		reportModel.setHeight(data.getHeight()) ;
    		reportModel.setDisplaytitle(data.isDisplaytitle()) ;
    		reportModel.setTitle(data.getTitle()) ;
    		reportModel.setNeckheight(data.getNeckheight()) ;
    		reportModel.setNeckwidth(data.getNeckwidth()) ;
    		reportModel.setColorstr(data.getColorstr()) ;
    		reportModel.setMarginright(data.getMarginright()) ;
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
	
    	return createModelAndView(view, report, request , reportModel , true ,true);
	}
    
    /**
     * 选择数据模型
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "selcube/{reportid}", name="selcube" , type="design",subtype="query")
	public ModelAndView selcube(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/selcube") , orgi) ;
    	view.addObject("cubePackageList", CubeFactory.getCubeInstance().getPublishedCubeDicList(orgi, super.getUser(request))) ;
    	view.addObject("cubeList", CubeFactory.getCubeInstance().getPublishedCubeListByDic(orgi , super.getUser(request) , "0")) ;
    	view.addObject("reportid", reportid) ;
    	if(request.getParameter("modelid")!=null && request.getParameter("modelid").length()>0){
    		view.addObject("modelid", request.getParameter("modelid")) ;
    	}
    	return view;
	}
    
    
    @RequestMapping(value="/{reportid}/{modelid}/restore/{direction}" , name="restore" , type="design",subtype="custom")
    public ModelAndView restore(HttpServletRequest request , @PathVariable String orgi,@PathVariable String modelid, @PathVariable String reportid, @PathVariable String direction) throws Exception{
    	ResponseData responseData = super.createManageResponse("redirect:/{orgi}/design/player/{reportid}.html?msgcode=S_REPORT_10020001");
    	
    	long flowid = System.currentTimeMillis();
    	if(request.getSession().getAttribute("flowid")!=null){
    		flowid = Long.parseLong(request.getSession().getAttribute("flowid").toString());
    	}
    	DetachedCriteria criteria = DetachedCriteria.forClass(ReportOperations.class).add(Restrictions.eq("reportid", reportid)).add(Restrictions.eq("userid", super.getUser(request).getId()));
				
    	if("back".equals(direction)){
    		criteria.addOrder(Order.desc("createtime")).add(Restrictions.lt("flowid", flowid));
    	}else{
    		criteria.addOrder(Order.asc("createtime")).add(Restrictions.gt("flowid", flowid));
    	}
    	
    	List<ReportOperations> operations = super.getService().findAllByCriteria(criteria);
    	
    	if(operations!=null&&operations.size()>0){
    		PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    		report.setReportcontent(operations.get(0).getReportcontent());
    		report.setReport(null);
    		/**
    		 * 更新缓存
    		 */
        	/**
        	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
        	 */
    		CacheHelper.getDistributedCacheBean().update(RivuTools.genReportCacheID(report.getId(), super.getUser(request) , false), orgi , report) ;
    		
    		/**
        	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
        	 */
    		CacheHelper.getDistributedCacheBean().update(RivuTools.genReportCacheID(report.getId(), super.getUser(request) , true), orgi , report) ;
    		
    		request.getSession().setAttribute("flowid", operations.get(0).getFlowid());
    		
    		
    	}else{//没找到需要替换的历史版本
    		responseData.setPage("redirect:/{orgi}/design/player/{reportid}.html?msgcode=E_REPORT_10020001");
    		
    	}
    	ModelAndView view = request(responseData , orgi) ;
    	return view;
    }
    
    /**
     * 选择数据模型
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "cubedic/{dicid}", name="selcube" , type="design",subtype="query")
	public ModelAndView cubedic(HttpServletRequest request , @PathVariable String  orgi ,  @PathVariable String  dicid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/cubedic") , orgi) ;
    	view.addObject("cubeList", CubeFactory.getCubeInstance().getPublishedCubeListByDic(orgi , super.getUser(request) , dicid)) ;
    	return view;
	}
    
    
    
    /**
     * 保存图表模式
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "filterdrag/{reportid}/{modelid}", name="filterdrag" , type="design",subtype="query")
	public ModelAndView filterdrag(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid,@Valid ReportFilter reportFilter) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/loadfiltervalues") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null){
    		for(ReportFilter rf : RivuTools.getRequestFilters(analyzerReport.getFilters())){
    			if(reportFilter.getId().equals(rf.getId())){
    				reportFilter = rf ;
    				StringBuffer strb = new StringBuffer() , temp = new StringBuffer();
    				if(request.getParameter("filter")!=null){
    					if(reportFilter.getDataname()!=null){
    						if(RivuDataContext.CubeEnum.CUBE.toString().equals(request.getParameter("type"))){
    							temp.append(request.getParameter("filter").replaceAll(",", "\\(-=-\\)"));
    						}else{
    							temp.append(request.getParameter("filter")) ;
    						}
    					}
    				}
    				boolean find = false ;
    				if(!StringUtils.isBlank(reportFilter.getRequestvalue())){
    					for(String ft : reportFilter.getRequestvalue().split(RivuDataContext.DEFAULT_VALIUE_SPLIT)){
        					ft = ft.replaceAll("\\(-=-\\)", ",");
        					temp = new StringBuffer(temp.toString().replaceAll("\\(-=-\\)", ","));
        					if(strb.toString().indexOf(ft)<0){
        						if(!ft.equals(temp.toString()) || "true".equalsIgnoreCase(request.getParameter("selected"))){
    	    						if(strb.length() >0){
    	    							strb.append(RivuDataContext.DEFAULT_VALIUE_SPLIT) ;
    	    						}
    	    						strb.append(ft) ;
        						}
        					}
        					if(ft.equals(temp.toString())){
        						find = true ;
        					}
        				}
    				}
    				if(!find && "true".equalsIgnoreCase(request.getParameter("selected"))){
    					if(strb.length()>0){
    						strb.append(RivuDataContext.DEFAULT_VALIUE_SPLIT);
    					}
    					strb.append(temp.toString()) ;
    				}
    				reportFilter.setRequestvalue(strb.toString().replaceAll("\\(-=-\\)", ",")) ;
    				view.addObject("filter", reportFilter);
    				break ;
    			}
    		}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
	
    	return createModelAndView(view, report, request , reportModel , true ,false);
	}
    
    /**
     * 保存图表模式
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "viewQuery/{reportid}/{modelid}", name="viewQuery" , type="design",subtype="query")
	public ModelAndView viewQuery(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid,@Valid String t , @Valid String opt) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/viewQuery") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	return createModelAndView(view, report, request , reportModel , true ,true);
    }
    
    /**
     * 保存图表模式
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "editQuery/{reportid}/{modelid}", name="editQuery" , type="design",subtype="query")
	public ModelAndView editQuery(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid,@Valid String t , @Valid String opt) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/player/datadiv") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid , true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel!=null && request.getParameter("query")!=null){
    		reportModel.setQuerytext(request.getParameter("query")) ;
    	}
    	
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , true) ;
    	
    	return createModelAndView(view, report, request , reportModel , true ,true);
    }
    
    /**
     * 保存图表模式
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "exportdata/{reportid}/{modelid}", name="exportdata" , type="design",subtype="query")
	public ModelAndView exportdata(HttpServletRequest request , HttpServletResponse response , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid,@Valid String t , @Valid String opt, @Valid String keyid) throws Exception{
    	
    	ModelAndView view = null;
    	if(request.getParameter("fresh")!=null){
    		view = request(super.createManageResponse("/pages/design/player/exportfresh") , orgi) ;
    		view.addObject("url", request.getRequestURL()+"?"+request.getQueryString());
    	}else{
    		view = request(super.createManageResponse("/pages/design/player/export") , orgi) ;
    		view.addObject("url", request.getRequestURL()+"?"+request.getQueryString()+"&fresh=fresh");
    	}
    	
    	
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	/**
    	 * 新创建导出任务规则：
    	 * 		1、当前任务已经执行完毕，文件系统中存在导出的文件，并且文件未过期
    	 * 		2、如果文件已过期，则将文件删除掉，同时创建一个新的  JobDetail，然后将这个JobDetail加入到执行任务队列中，即可返回
    	 * 		3、如果当前任务正在执行，则不作任何处理，等待即可
    	 */
    	if(reportModel!=null && keyid!=null && keyid.length()>0){
    		reportModel.setDisplaytitle(true) ;
			reportModel.setPublishtype("modelpublish") ;
			reportModel.setIsexport(true);

			if(request.getParameter("startTime")!=null){
				reportModel.setStart(request.getParameter("startTime"));
	    	}
	    	if(request.getParameter("endTime")!=null){
	    		reportModel.setEnd(request.getParameter("endTime"));
	    	}
	    	reportModel.setExporttitle(request.getParameter("tl")!=null ? request.getParameter("tl") : reportModel.getName()!=null && reportModel.getName().length()>0 ? reportModel.getName() : report.getName()) ;
			
			if(request.getParameter("wt").equals("pdf")){
//				exportFile = new RivuPDFUtil(reportModel, analyzerReport , response.getOutputStream());
				keyid = keyid+"_pdf";
			}
			if(request.getParameter("wt").equals("excel")){
				keyid = keyid+"_excel";
//				exportFile = new RivuExcelUtil(reportModel, analyzerReport , response.getOutputStream());
			}
			if(request.getParameter("wt").equals("csv")){
				keyid = keyid+"_csv";
//				exportFile = new RivuCSVUtil(reportModel, analyzerReport , response.getOutputStream());
			}
			if(request.getParameter("wt").equals("xml")){
				keyid = keyid+"_xml";
//				exportFile = new RivuCSVUtil(reportModel, analyzerReport , response.getOutputStream());
			}
			/**
			 * 设置导出数据
			 */
//			reportModel.setExport(exportFile) ;
			reportModel.setIsexport(true);
			
//			view = createModelAndView(view , true , report , request , reportModel);
			
			if("edit".equals(request.getParameter("t"))){
				reportModel.setEditview("edit") ;
			}
			
//			if(view.getModelMap().get("reportData")!=null){//
//	    		ReportData reportData = (ReportData) view.getModelMap().get("reportData") ;
//	    		if(reportData.getData()!=null&&reportData.getData().size()>0){
//	    			try {
//	    				if(RivuDataContext.DataBaseTYPEEnum.HIVE.toString().equals(reportModel.getDbType())){
//	    					reportModel.getExport().setReportData(reportData);
//							reportModel.getExport().createFile(false);
//							
//	    				}else{
//	    					reportModel.getExport().setReportData(reportData);
//							reportModel.getExport().createFile(true);
//	    				}
//	    				reportModel.getExport().close();//把数据写出
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//	    			
//	    		}
//    			
//				
//	    	}
			view.addObject("report", report) ;
			view.addObject("reportModel", reportModel) ;
			view.addObject("wt", request.getParameter("wt")) ;
			view.addObject("keyid", request.getParameter("keyid")) ;
			view.addObject("total", request.getParameter("total")) ;
			if(keyid!=null){
				/**
				 * 跳转
				 */
				File exortFile = RivuTools.getExportFile(analyzerReport, request, reportModel, orgi, keyid) ;
				JobDetail job = RivuTools.getRunningJob(orgi, keyid);
				if(exortFile!=null && job == null){
					view.addObject("length", exortFile.length()) ;
					view.addObject("name", reportModel.getTitle()) ;
				}else{
					if(job != null){
						view.addObject("jobDetail", job) ;
					}else{
						/**
						 * 优先查询分布式，hostName不为空即表示在分布式中存在已经导出的文件
						 */
						String hostName = null ;
		    			/**
		    			 * 如果hostName不为空，则跳转到服务器，修改以下服务器端口获取
		    			 */
		    			if(hostName!=null){
			    			String port = (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("com.rivues.cluster."+hostName+".port", orgi) ;
			    			StringBuffer param = new StringBuffer();
			    			if(t!=null){
			    				param.append("t=").append(t) ;
			    			}
			    			if(opt!=null){
			    				param.append("&opt=").append(opt) ;
			    			}
			    			if(keyid!=null){
			    				param.append("&keyid").append(keyid) ;
			    			}
			    			if(request.getParameter("wt")!=null){
			    				param.append("&wt").append(request.getParameter("wt")) ;
			    			}
			    			if(request.getParameter("tl")!=null){
			    				param.append("&tl").append(request.getParameter("tl")) ;
			    			}
			    			view = request(super.createManageResponse("redirect:http://"+hostName+":"+port+"/{orgi}/design/player/exportdata/{reportid}/{modelid}.html?"+param.toString()) , orgi) ;
		    			}else{
		    				JobDetail jobDetail = RivuTools.createExportJobDetail(report.getName() , analyzerReport, request, reportModel, super.getUser(request), keyid , request.getParameter("wt"),request.getParameter("fresh")==null?true:false) ;
			    			if(jobDetail!=null){
			    				view.addObject("jobDetail", jobDetail) ;
			    			}
		    			}
					}
				}
			}
    	}
    	return view ;
    }
    
    /**
     * 保存图表模式
     * @param request
     * @param orgi
     * @param reportid
     * @param modelid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "export/{reportid}/{modelid}", name="export" , type="design",subtype="query")
	public ModelAndView export(HttpServletRequest request , HttpServletResponse response , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String modelid,@Valid String t , @Valid String opt, String keyid) throws Exception{
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid,true) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	ModelAndView view = null ;
    	/**
    	 * 新创建导出任务规则：
    	 * 		1、当前任务已经执行完毕，文件系统中存在导出的文件，并且文件未过期
    	 * 		2、如果文件已过期，则将文件删除掉，同时创建一个新的  JobDetail，然后将这个JobDetail加入到执行任务队列中，即可返回
    	 * 		3、如果当前任务正在执行，则不作任何处理，等待即可
    	 */
    	if(reportModel!=null){
    		if(request.getParameter("wt").equals("pdf")){
				keyid = keyid+"_pdf";
			}else if(request.getParameter("wt").equals("excel")){
				keyid = keyid+"_excel";
			}else if(request.getParameter("wt").equals("csv")){
				keyid = keyid+"_csv";
			}else if(request.getParameter("wt").equals("xml")){
				keyid = keyid+"_xml";
			}else{
				keyid = null ;
			}
    		if(keyid!=null){
	    		File exportFile = RivuTools.getExportFile(analyzerReport, request, reportModel, orgi, keyid) ;
	    		if(exportFile!=null){
		    		String title = request.getParameter("tl")!=null ? request.getParameter("tl") : reportModel.getName()!=null && reportModel.getName().length()>0 ? reportModel.getName() : report.getName() ;
					if(request.getParameter("wt").equals("pdf")){
						if(request.getParameter("startTime")!=null){
							reportModel.setStart(request.getParameter("startTime"));
				    	}
				    	if(request.getParameter("endTime")!=null){
				    		reportModel.setEnd(request.getParameter("endTime"));
				    	}
						response.addHeader("Content-Disposition","attachment;filename=\"" + RivuTools.cvChar(title) + "\".pdf");  
					}
					response.setContentType("charset=UTF-8;application/octet-stream");
					if(request.getParameter("wt").equals("excel")){
						if(request.getParameter("startTime")!=null){
							reportModel.setStart(request.getParameter("startTime"));
				    	}
				    	if(request.getParameter("endTime")!=null){
				    		reportModel.setEnd(request.getParameter("endTime"));
				    	}
						response.addHeader("Content-Disposition","attachment;filename=\"" + RivuTools.cvChar(title) + "\".xlsx");  
					}
					if(request.getParameter("wt").equals("csv")){
						if(request.getParameter("startTime")!=null){
							reportModel.setStart(request.getParameter("startTime"));
				    	}
				    	if(request.getParameter("endTime")!=null){
				    		reportModel.setEnd(request.getParameter("endTime"));
				    	}
						response.addHeader("Content-Disposition","attachment;filename=\"" + RivuTools.cvChar(title) + "\".csv");  
					}
					if(request.getParameter("wt").equals("xml")){
						if(request.getParameter("startTime")!=null){
							reportModel.setStart(request.getParameter("startTime"));
				    	}
				    	if(request.getParameter("endTime")!=null){
				    		reportModel.setEnd(request.getParameter("endTime"));
				    	}
						response.addHeader("Content-Disposition","attachment;filename=\"" + RivuTools.cvChar(title) + "\".xml");  
					}
					FileInputStream input = new FileInputStream(exportFile) ;
					try{
						byte[] data = new byte[1024] ;
						int len = 0 ;
						OutputStream output = response.getOutputStream() ;
						while((len = input.read(data))>0){
							output.write(data, 0, len) ;
						}
					}catch(Exception ex){
						ex.printStackTrace();
					}finally{
						input.close() ;
					}
					
	    		}else{
	    			String hostName = null ;
	    			/**
	    			 * 如果hostName不为空，则跳转到服务器，修改以下服务器端口获取
	    			 */
	    			if(hostName!=null){
		    			String port = (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("com.rivues.cluster."+hostName+".port", orgi) ;
		    			
		    			StringBuffer param = new StringBuffer();
		    			if(t!=null){
		    				param.append("t=").append(t) ;
		    			}
		    			if(opt!=null){
		    				param.append("&opt=").append(opt) ;
		    			}
		    			if(keyid!=null){
		    				param.append("&keyid").append(keyid) ;
		    			}
		    			if(request.getParameter("wt")!=null){
		    				param.append("&wt").append(request.getParameter("wt")) ;
		    			}
		    			if(request.getParameter("tl")!=null){
		    				param.append("&tl").append(request.getParameter("tl")) ;
		    			}
		    			view = request(super.createManageResponse("redirect:http://"+hostName+":"+port+"/{orgi}/design/player/export/{reportid}/{modelid}.html?"+param.toString()) , orgi) ;
	    			}
	    		}
    		}
    	}
    	return view ;
    }
    
} 